package com.wang.thread;

import com.wang.util.LeakyBucket;
import org.joda.time.DateTime;

import java.io.*;
import java.net.Socket;

/**
 * 服务器线程
 * Created by wang on 2017/5/3.
 */
public class ServerThread implements Runnable {
    private Socket socket=null;
    private InputStream inputStream= null;
    private InputStreamReader reader= null;
    private BufferedReader bufferedReader= null;
    private OutputStream outputStream = null;
    private PrintWriter out = null;
     //注入 socket
    public ServerThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取客户端请求信息
            inputStream = socket.getInputStream();
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            String info;
            while ((info = bufferedReader.readLine()) != null) {
                System.out.println("客户端："+info);
            }
            socket.shutdownInput();
            //获取输出流，向客户端发出响应
            outputStream = socket.getOutputStream();
            out = new PrintWriter(outputStream);
            out.write("欢迎测试："+ DateTime.now());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                if (inputStream != null)
                    inputStream.close();
                if (reader!=null)
                    reader.close();
                if (bufferedReader!=null)
                    bufferedReader.close();
                if (socket!=null)
                    socket.close();
                if (outputStream!=null)
                    outputStream.close();
                if (out!=null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
